/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dms_system_gui;

import database_interaction.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author james
 */
public class LoginForm extends javax.swing.JFrame {

    /**
     * Creates new form LoginForm
     */
    public LoginForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textBoxUser = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        textboxPassword = new javax.swing.JPasswordField();
        butLogin = new javax.swing.JButton();
        labelStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(273, 246));
        setMinimumSize(new java.awt.Dimension(273, 246));
        setType(java.awt.Window.Type.UTILITY);

        jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
        jLabel1.setText("Dealer Management System");

        jLabel2.setText("Username");

        textBoxUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textBoxUserActionPerformed(evt);
            }
        });
        textBoxUser.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                textBoxUserKeyTyped(evt);
            }
        });

        jLabel3.setText("Password");

        textboxPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                textboxPasswordKeyTyped(evt);
            }
        });

        butLogin.setLabel("Login");
        butLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butLoginActionPerformed(evt);
            }
        });

        labelStatus.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        labelStatus.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        labelStatus.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        labelStatus.setVerticalTextPosition(javax.swing.SwingConstants.TOP);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textBoxUser)
                            .addComponent(textboxPassword)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(butLogin)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
                    .addComponent(jLabel1))
                .addGap(32, 32, 32))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textBoxUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textboxPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(butLogin)
                        .addGap(0, 70, Short.MAX_VALUE))
                    .addComponent(labelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void textBoxUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textBoxUserActionPerformed
       
    }//GEN-LAST:event_textBoxUserActionPerformed

    private void butLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butLoginActionPerformed
        login(textBoxUser.getText(), 
              String.valueOf(textboxPassword.getPassword()));
    }//GEN-LAST:event_butLoginActionPerformed

    private void textBoxUserKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textBoxUserKeyTyped
        if(evt.getKeyChar() == '\n')
            login(textBoxUser.getText(), 
              String.valueOf(textboxPassword.getPassword()));
        else
            labelStatus.setText("");
    }//GEN-LAST:event_textBoxUserKeyTyped

    private void textboxPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textboxPasswordKeyTyped
        if(evt.getKeyChar() == '\n')
            login(textBoxUser.getText(), 
              String.valueOf(textboxPassword.getPassword()));
        else
            labelStatus.setText("");
    }//GEN-LAST:event_textboxPasswordKeyTyped

    private void login(String username, String password){
        try {
            Database db = new Database("jdbc:mysql://localhost/dms");
            db.connect("root", "");
            
            ResultSet result = 
            db.executeQuery(new SelectQuery("users",
                                            String.format("username = '%s' AND password = '%s'",
                                                          username,
                                                          password))
                            );
            if(result.first()){
                new MainForm(result.getInt("auth_level"),
                             result.getInt("id"),
                             db)
                            .setVisible(true);
                UpdateQuery loginUser = new UpdateQuery("users", "id = " + result.getInt("id"));
                loginUser.addParameter(new Int(1), "status");
                db.executeQuery(loginUser);
                this.setVisible(false);
            }
            else{
                labelStatus.setText("Username or Password are incorrect.");
            }
        } catch (JDBCException ex) {
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            labelStatus.setText("Username or Password are incorrect.");
        } catch (SQLException ex) {
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            labelStatus.setText("Could not connect to server.");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            labelStatus.setText("Could not connect to server.");
        } catch (InstantiationException ex) {
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            labelStatus.setText("Could not connect to server.");
        } catch (IllegalAccessException ex) {
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            labelStatus.setText("Could not connect to server.");
        }
    }
            
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton butLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel labelStatus;
    private javax.swing.JTextField textBoxUser;
    private javax.swing.JPasswordField textboxPassword;
    // End of variables declaration//GEN-END:variables
}
